import { mapState } from 'vuex'
import { getValueFromXml,randomUploadFileName } from '@/plugins/utils';
import { fileUploadUrl } from '@/api/api';



export const coverImg = {
  computed: {
    ...mapState({
      fileUploadData: state => state.components.fileUploadData,
      site_id: (state) => state.components.id
    }),
  },
  created(){
    if(!window.html2canvas){
      this.dynamicsLoadScript(this.env.publicPath + 'js/html2canvas.min.js', 'html2canvas')
    }
  },
  methods: {
    dataURLToBlob(dataURL) {
      var BASE64_MARKER = ';base64,';
      var raw;
      var contentType;
      var parts;
      if (dataURL.indexOf(BASE64_MARKER) == -1) {
          parts = dataURL.split(',');
          contentType = parts[0].split(':')[1];
          raw = decodeURIComponent(parts[1]);

          return new Blob([raw], {type: contentType});
      }

      parts = dataURL.split(BASE64_MARKER);
      contentType = parts[0].split(':')[1];
      raw = window.atob(parts[1]);
      var rawLength = raw.length;

      var uInt8Array = new Uint8Array(rawLength);

      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }

      return new Blob([uInt8Array], {type: contentType});
    },
    async print(el, w, h, s) {
      let fileUploadData = _.cloneDeep(this.fileUploadData);
      let canvasVisibles = [];
      const canvasDoms = el.querySelectorAll('canvas');
      _.forEach(canvasDoms, (canvas) => {
        canvas.style.display = "none";
        canvasVisibles.push(canvas);
      })
      window.html2canvas(el,{
        useCORS: true,
        async: true,
        logging: false,
        scale: s,
        // allowTaint: true,
        width: w,
        height: h,
      }).then( (canvas) => {
        _.forEach(canvasVisibles, (dom) => {
          dom.style.display = "block";
        })
        let canResultBase64 = canvas.toDataURL("image/jpeg", 0.8);
        let blobObj = this.dataURLToBlob(canResultBase64);
        var filename =  randomUploadFileName(this.site_id) + ".jpeg";
        fileUploadData.key += filename;
        let option = {
          action: fileUploadUrl,
          onSuccess: this.onSuccess,
          onError: this.onError,
          data: fileUploadData,
          fileKey: "file",
          file: blobObj,
        }
        this.upload(option);
      });
    },
    upload(option){
      var xhr = new XMLHttpRequest();
      var action = option.action;
      var formData = new FormData();
      if (option.data) {
        Object.keys(option.data).forEach( (key) => {
          formData.append(key, option.data[key]);
        });
      }
      formData.append(option.fileKey, option.file);
      xhr.onerror = (e) => {
        option.onError(e);
      };
      xhr.onload = () => {
        if (xhr.status < 200 || xhr.status >= 300) {
          return option.onError(this.getError(action, option, xhr));
        }
        option.onSuccess(this.getBody(xhr));
      };
      xhr.open('post', action, true);
      var headers = option.headers || {};
      for (var key in headers) {
        if (Object.prototype.hasOwnProperty.call(headers, key) && headers[key] !== null) {
          xhr.setRequestHeader(key, headers[key]);
        }
      }
      xhr.send(formData);
      return xhr;
    },

    onSuccess(response){
      let url = getValueFromXml(response);
      url = _.replace(url, 'http', 'https');
      url = _.replace(url, 'file', 'static');
      url = _.replace(url, '.s3.sinaapp.com', '');
      this.$emit('htmlToCanvas', url);
    },
    getBody(xhr) {
      var text = xhr.responseText || xhr.response;
      if (!text) {
        return text;
      }
      try {
        return JSON.parse(text);
      } catch (e) {
        return text;
      }
    },
    getError(action, option, xhr) {
      var msg = void 0;
      if (xhr.response) {
        msg = '' + (xhr.response.error || xhr.response);
      } else if (xhr.responseText) {
        msg = '' + xhr.responseText;
      } else {
        msg = 'fail to post ' + action + ' ' + xhr.status;
      }
      var err = new Error(msg);
      err.status = xhr.status;
      err.method = 'post';
      err.url = action;
      return err;
    },
    onError(e){
      console.log(e);
    },
  },
};
